package com.tsfyun.scm.util;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.tsfyun.common.base.enums.WxMenuEnum;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.dto.support.WxMenuItemDTO;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.security.AlgorithmParameters;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;
import java.util.Objects;

public class WXUtil {

    private static final String token = "s02cca18a0fc37dbm902fbab5e9f50bt";

    private static final String LIMIT_CODE = "48006";

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);

        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @return
     */
    public static boolean checkSignature(String signature,String timestamp,String nonce) {
        String[] str = new String[]{token, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = SHA1.encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    /**
     * URL编码
     * @param url
     * @return
     */
    public static String URLEncoder(String url){
        try{
            url = URLEncoder.encode(url,"UTF-8");
        }catch (Exception e){

        }
        return url;
    }

    /**
     * SHA1加密
     * @param decript
     * @return
     */
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取时间戳
     */
    public static String timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     * 验证微信菜单参数
     * @param menu
     */
    public static void validMenu(WxMenuItemDTO menu) {
        WxMenuEnum wxMenuEnum = WxMenuEnum.of(menu.getType());
        if(Objects.equals(wxMenuEnum,WxMenuEnum.CLICK) && StringUtils.isEmpty(menu.getKey())) {
            throw new ServiceException("菜单类型为click点击时，菜单key值不能为空");
        }
        if((Objects.equals(wxMenuEnum,WxMenuEnum.VIEW) || Objects.equals(wxMenuEnum,WxMenuEnum.MINIPROGRAM))
                && StringUtils.isEmpty(menu.getUrl())) {
            throw new ServiceException("菜单类型为view网页时，菜单url值不能为空");
        }
        if(Objects.equals(wxMenuEnum,WxMenuEnum.MINIPROGRAM) && StringUtils.isEmpty(menu.getPagepath())) {
            throw new ServiceException("菜单类型为miniprogram小程序时，菜单pagepath值不能为空");
        }
    }

    //公众号调用或第三方平台帮公众号调用对公众号的所有api调用（包括第三方帮其调用）次数进行清零
    //https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=ACCESS_TOKEN
}
